<?php
function getlocations($service){
	// Get Band event

	$eventURL = "http://www.google.com/calendar/feeds/rf74odghk1gm8d16nl2kqtj5jk%40group.calendar.google.com/private/full/hep03m75364po836pl7fbglrmo";
	try {
		$event = $service->getCalendarEventEntry($eventURL);
		$locationsrawlist = $event->content;
		$locations = explode("%@", $locationsrawlist);
	} catch (Zend_Gdata_App_Exception $e) {
		echo "Error: " . $e->getMessage();
	}

	return $locations;
}

function recentURL($includeParams)
{
	$http = "";
	if ($includeParams)
	{
		$http = $_SERVER["REQUEST_URI"];
	}
	else
	{
		$http = $_SERVER["PHP_SELF"];
	}
	return toSafeURL($http);
}


function getbands($service){
	// Get Band event

	$eventURL = "http://www.google.com/calendar/feeds/rf74odghk1gm8d16nl2kqtj5jk%40group.calendar.google.com/private/full/9k1boaq9gppcuiui8f34uikcno";
	try {
		$event = $service->getCalendarEventEntry($eventURL);
		$bandsrawlist = $event->content;
		$bands = explode("@", $bandsrawlist);
	} catch (Zend_Gdata_App_Exception $e) {
		echo "Error: " . $e->getMessage();
	}

	return $bands;
}

function showAlert($message)
{
	echo '<div class="ui-widget alert"><DIV id="alertmessage" style="PADDING-BOTTOM: 0px; PADDING-LEFT: 0.7em; PADDING-RIGHT: 0.7em; PADDING-TOP: 0px" class="ui-state-error ui-corner-all">
				<P><SPAN style="FLOAT: left; MARGIN-RIGHT: 0.3em" class="ui-icon ui-icon-alert"></SPAN><STRONG>' . $message . '</STRONG></P></DIV></div>';
	echo '<script type="text/javascript">
			$("#alertmessage").delay(5000).fadeTo(400,0);
			</script>';
}

function runpostbackactions($url, $service) {
	//Run postback actions
	if (isset($_POST['action']))
	{
		//Delete Event
		if ($_POST['action'] == 'deleteevent')
		{
			deleteEventById($service, $url, $_POST['eventid']);
			showAlert('Event Deleted');
		}
		//Add Event
		elseif ($_POST['action'] == 'addevent')
		{
			$date = $_POST['startdate'];
			$date .= ' ' . $_POST['hour'] . ':' . $_POST['minutetens'] . $_POST['minuteones'] . ' ' . $_POST['ampm'];
			//echo $date;
			$datetime = new DateTime($date);
			$datetime->format('n');
			$yearmonthday = $datetime->format('Y') . '-' . $datetime->format('m') . '-' . $datetime->format('d');
			$startTime = $datetime->format('H') . ':' . $datetime->format('i');
			addevent($_POST['title'], $_POST['where'], $yearmonthday, $startTime, '23:59', $url, $service);
			showAlert('Event Added');
		}
		elseif ($_POST['action'] == 'addband')
		{
			$eventURL = "http://www.google.com/calendar/feeds/rf74odghk1gm8d16nl2kqtj5jk%40group.calendar.google.com/private/full/9k1boaq9gppcuiui8f34uikcno";
			try {
				$event = $service->getCalendarEventEntry($eventURL);
				$bandsrawlist = $event->content;
				$event->content = $service->newContent($event->content . '@' . $_POST['newband']);
				$event->save();
				showAlert('Band Added');
			} catch (Zend_Gdata_App_Exception $e) {
				echo "Error: " . $e->getMessage();
			}
		}		
		elseif ($_POST['action'] == 'deleteband')
		{
			$eventURL = "http://www.google.com/calendar/feeds/rf74odghk1gm8d16nl2kqtj5jk%40group.calendar.google.com/private/full/9k1boaq9gppcuiui8f34uikcno";
			try {
				$event = $service->getCalendarEventEntry($eventURL);
				$bandsrawlist = $event->content;
				$bands = explode("@", $bandsrawlist);
				$i = 0;
				foreach ($bands as $band)
				{
					if ($band == $_POST['title'])
					{
						unset($bands[$i]);
						$newbands = array_values($bands);
						$updatedbands = implode('@',$newbands);
						$event->content = $service->newContent($updatedbands);
						$event->save();
						showAlert('Band Deleted');
					}
					$i++;	
				}
			} catch (Zend_Gdata_App_Exception $e) {
				echo "Error: " . $e->getMessage();
			}
		}
		elseif ($_POST['action'] == 'addlocation')
		{
			$eventURL = "http://www.google.com/calendar/feeds/rf74odghk1gm8d16nl2kqtj5jk%40group.calendar.google.com/private/full/hep03m75364po836pl7fbglrmo";
			try {
				$event = $service->getCalendarEventEntry($eventURL);
				$locationsrawlist = $event->content;
				$locations = explode("%@", $locationsrawlist);
				$newlocation = $_POST['newname'] . '#@' . $_POST['newcity'] . '#@' . $_POST['newstate'];
				array_push($locations, $newlocation);
				$newlocationsrawlist = implode('%@', $locations);
				$event->content = $service->newContent($newlocationsrawlist);
				$event->save();
				showAlert('Venue Added');
			} catch (Zend_Gdata_App_Exception $e) {
				echo "Error: " . $e->getMessage();
			}
		}
		elseif ($_POST['action'] == 'deletelocation')
		{
			$eventURL = "http://www.google.com/calendar/feeds/rf74odghk1gm8d16nl2kqtj5jk%40group.calendar.google.com/private/full/hep03m75364po836pl7fbglrmo";
			try {
				$event = $service->getCalendarEventEntry($eventURL);
				$locationsrawlist = $event->content;
				$locations = explode("%@", $locationsrawlist);
				$i = 0;
				foreach ($locations as $location)
				{
					$locationdetails = explode('#@', $location);
					if (count($locationdetails) > 1)
					{
						$deletetarget = $locationdetails[0] . ' - ' . $locationdetails[1] . ', ' . $locationdetails[2];
						if ($deletetarget == $_POST['where'])
						{
							unset($locations[$i]);
							$newlocations = array_values($locations);
							$updatedlocations = implode('%@',$newlocations);
							$event->content = $service->newContent($updatedlocations);
							$event->save();
							showAlert('Location Deleted');
						}
					}
					$i++;
				}
			} catch (Zend_Gdata_App_Exception $e) {
				echo "Error: " . $e->getMessage();
			}
		}
	}
}

function addevent($fm_title, $fm_where, $fm_startdate, $fm_starttime, $fm_endtime, $url, $service)
{
	// Create a new entry using the calendar service's magic factory method
	$event= $service->newEventEntry();
	// Populate the event with the desired information
	// Note that each attribute is crated as an instance of a matching class
	$event->title = $service->newTitle($fm_title);
	$event->where = array($service->newWhere($fm_where));
	$event->content =
	$service->newContent("Rock Show");
	// Set the date using RFC 3339 format.
	$startDate = $fm_startdate;
	$startTime = $fm_starttime;
	$endDate = $fm_startdate;
	$endTime = $fm_endtime;
	$tzOffset = "-05";
	$when = $service->newWhen();
	$when->startTime = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
	$when->endTime = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";
	$event->when = array($when);
	// Upload the event to the calendar server
	// A copy of the event as it is recorded on the server is returned
	$newEvent = $service->insertEvent($event, $url);
}


//Creates a new service to call Google Data API
function newservice($username, $password)
{
	// Authenticate &
	// Create an instance of the Calendar service
	$service = new Zend_Gdata_Calendar(getClientLoginHttpClient($username,$password));
	return $service;
}


/**
 * Returns the full URL of the current page, based upon env variables
 *
 * Env variables used:
 * $_SERVER['HTTPS'] = (on|off|)
 * $_SERVER['HTTP_HOST'] = value of the Host: header
 * $_SERVER['SERVER_PORT'] = port number (only used if not http/80,https/443)
 * $_SERVER['REQUEST_URI'] = the URI after the method of the HTTP request
 *
 * @return string Current URL*/
function getCurrentUrl()
{
	global $_SERVER;

	/**
	 * Filter php_self to avoid a security vulnerability.
	 */
	$php_request_uri = htmlentities(substr($_SERVER['REQUEST_URI'], 0, strcspn($_SERVER['REQUEST_URI'], "\n\r")), ENT_QUOTES);

	if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') {
		$protocol = 'https://';
	} else {
		$protocol = 'http://';
	}
	$host = $_SERVER['HTTP_HOST'];
	if ($_SERVER['SERVER_PORT'] != '' &&
	(($protocol == 'http://' && $_SERVER['SERVER_PORT'] != '80') ||
	($protocol == 'https://' && $_SERVER['SERVER_PORT'] != '443'))) {
		$port = ':' . $_SERVER['SERVER_PORT'];
	} else {
		$port = '';
	}
	return $protocol . $host . $port . $php_request_uri;
}

/**
 * Returns a HTTP client object with the appropriate headers for communicating
 * with Google using the ClientLogin credentials supplied.
 *
 * @param  string $user The username, in e-mail address format, to authenticate
 * @param  string $pass The password for the user specified
 * @return Zend_Http_Client*/
function getClientLoginHttpClient($user, $pass)
{
	$service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;

	$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
	return $client;
}

/**
 * Outputs an HTML unordered list (ul), with each list item representing a
 * calendar in the authenticated user's calendar list.
 *
 * @param  Zend_Http_Client $client The authenticated client object
 * @return void*/
function outputCalendarList($client)
{
	$gdataCal = new Zend_Gdata_Calendar($client);
	$calFeed = $gdataCal->getCalendarListFeed();
	echo "<h1>" . $calFeed->title->text . "</h1>\n";
	echo "<ul>\n";
	foreach ($calFeed as $calendar) {
		echo "\t<li>" . $calendar->title->text . "</li>\n";
	}
	echo "</ul>\n";
}

/**
 * Outputs an HTML unordered list (ul), with each list item representing an
 * event on the authenticated user's calendar.  Includes the start time and
 * event ID in the output.  Events are ordered by starttime and include only
 * events occurring in the future.
 *
 * @param  Zend_Http_Client $client The authenticated client object
 * @return void
 */
function outputCalendar($client)
{
	$gdataCal = new Zend_Gdata_Calendar($client);
	$query = $gdataCal->newEventQuery();
	$query->setUser('default');
	$query->setVisibility('private');
	$query->setProjection('full');
	$query->setOrderby('starttime');
	$query->setFutureevents(true);
	$eventFeed = $gdataCal->getCalendarEventFeed($query);
	// option 2
	// $eventFeed = $gdataCal->getCalendarEventFeed($query->getQueryUrl());
	echo "<ul>\n";
	foreach ($eventFeed as $event) {
		echo "\t<li>" . $event->title->text .  " (" . $event->id->text . ")\n";
		// Zend_Gdata_App_Extensions_Title->__toString() is defined, so the
		// following will also work on PHP >= 5.2.0
		//echo "\t<li>" . $event->title .  " (" . $event->id . ")\n";
		echo "\t\t<ul>\n";
		foreach ($event->when as $when) {
			echo "\t\t\t<li>Starts: " . $when->startTime . "</li>\n";
		}
		echo "\t\t</ul>\n";
		echo "\t</li>\n";
	}
	echo "</ul>\n";
}

/**
 * Outputs an HTML unordered list (ul), with each list item representing an
 * event on the authenticated user's calendar which occurs during the
 * specified date range.
 *
 * To query for all events occurring on 2006-12-24, you would query for
 * a startDate of '2006-12-24' and an endDate of '2006-12-25' as the upper
 * bound for date queries is exclusive.  See the 'query parameters reference':
 * http://code.google.com/apis/gdata/calendar.html#Parameters
 *
 * @param  Zend_Http_Client $client    The authenticated client object
 * @param  string           $startDate The start date in YYYY-MM-DD format
 * @param  string           $endDate   The end date in YYYY-MM-DD format
 * @return void*/
function outputCalendarByDateRange($client, $startDate='2007-05-01',
$endDate='2007-08-01')
{
	$gdataCal = new Zend_Gdata_Calendar($client);
	$query = $gdataCal->newEventQuery();
	$query->setUser('default');
	$query->setVisibility('private');
	$query->setProjection('full');
	$query->setOrderby('starttime');
	$query->setStartMin($startDate);
	$query->setStartMax($endDate);
	$eventFeed = $gdataCal->getCalendarEventFeed($query);
	echo "<ul>\n";
	foreach ($eventFeed as $event) {
		echo "\t<li>" . $event->title->text .  " (" . $event->id->text . ")\n";
		echo "\t\t<ul>\n";
		foreach ($event->when as $when) {
			echo "\t\t\t<li>Starts: " . $when->startTime . "</li>\n";
		}
		echo "\t\t</ul>\n";
		echo "\t</li>\n";
	}
	echo "</ul>\n";
}

/**
 * Outputs an HTML unordered list (ul), with each list item representing an
 * event on the authenticated user's calendar which matches the search string
 * specified as the $fullTextQuery parameter
 *
 * @param  Zend_Http_Client $client        The authenticated client object
 * @param  string           $fullTextQuery The string for which you are searching
 * @return void*/
function outputCalendarByFullTextQuery($client, $fullTextQuery='tennis')
{
	$gdataCal = new Zend_Gdata_Calendar($client);
	$query = $gdataCal->newEventQuery();
	$query->setUser('default');
	$query->setVisibility('private');
	$query->setProjection('full');
	$query->setQuery($fullTextQuery);
	$eventFeed = $gdataCal->getCalendarEventFeed($query);
	echo "<ul>\n";
	foreach ($eventFeed as $event) {
		echo "\t<li>" . $event->title->text .  " (" . $event->id->text . ")\n";
		echo "\t\t<ul>\n";
		foreach ($event->when as $when) {
			echo "\t\t\t<li>Starts: " . $when->startTime . "</li>\n";
			echo "\t\t</ul>\n";
			echo "\t</li>\n";
		}
	}
	echo "</ul>\n";
}

/**
 * Creates an event on the authenticated user's default calendar with the
 * specified event details.
 *
 * @param  Zend_Http_Client $client    The authenticated client object
 * @param  string           $title     The event title
 * @param  string           $desc      The detailed description of the event
 * @param  string           $where
 * @param  string           $startDate The start date of the event in YYYY-MM-DD format
 * @param  string           $startTime The start time of the event in HH:MM 24hr format
 * @param  string           $endDate   The end date of the event in YYYY-MM-DD format
 * @param  string           $endTime   The end time of the event in HH:MM 24hr format
 * @param  string           $tzOffset  The offset from GMT/UTC in [+-]DD format (eg -08)
 * @return string The ID URL for the event.*/
function createEvent ($client, $title = 'Tennis with Beth',
$desc='Meet for a quick lesson', $where = 'On the courts',
$startDate = '2008-01-20', $startTime = '10:00',
$endDate = '2008-01-20', $endTime = '11:00', $tzOffset = '-08')
{
	$gc = new Zend_Gdata_Calendar($client);
	$newEntry = $gc->newEventEntry();
	$newEntry->title = $gc->newTitle(trim($title));
	$newEntry->where  = array($gc->newWhere($where));

	$newEntry->content = $gc->newContent($desc);
	$newEntry->content->type = 'text';

	$when = $gc->newWhen();
	$when->startTime = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
	$when->endTime = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";
	$newEntry->when = array($when);

	$createdEntry = $gc->insertEvent($newEntry);
	return $createdEntry->id->text;
}

/**
 * Creates an event on the authenticated user's default calendar using
 * the specified QuickAdd string.
 *
 * @param  Zend_Http_Client $client       The authenticated client object
 * @param  string           $quickAddText The QuickAdd text for the event
 * @return string The ID URL for the event
 */
function createQuickAddEvent ($client, $quickAddText) {
	$gdataCal = new Zend_Gdata_Calendar($client);
	$event = $gdataCal->newEventEntry();
	$event->content = $gdataCal->newContent($quickAddText);
	$event->quickAdd = $gdataCal->newQuickAdd(true);

	$newEvent = $gdataCal->insertEvent($event);
	return $newEvent->id->text;
}

/**
 * Creates a new web content event on the authenticated user's default
 * calendar with the specified event details. For simplicity, the event
 * is created as an all day event and does not include a description.
 *
 * @param  Zend_Http_Client $client    The authenticated client object
 * @param  string           $title     The event title
 * @param  string           $startDate The start date of the event in YYYY-MM-DD format
 * @param  string           $endDate   The end time of the event in HH:MM 24hr format
 * @param  string           $icon      URL pointing to a 16x16 px icon representing the event.
 * @param  string           $url       The URL containing the web content for the event.
 * @param  string           $height    The desired height of the web content pane.
 * @param  string           $width     The desired width of the web content pane.
 * @param  string           $type      The MIME type of the web content.
 * @return string The ID URL for the event.
 */
function createWebContentEvent ($client, $title = 'World Cup 2006',
$startDate = '2006-06-09', $endDate = '2006-06-09',
$icon = 'http://www.google.com/calendar/images/google-holiday.gif',
$url = 'http://www.google.com/logos/worldcup06.gif',
$height  = '120', $width = '276', $type = 'image/gif'
)
{
	$gc = new Zend_Gdata_Calendar($client);
	$newEntry = $gc->newEventEntry();
	$newEntry->title = $gc->newTitle(trim($title));

	$when = $gc->newWhen();
	$when->startTime = $startDate;
	$when->endTime = $endDate;
	$newEntry->when = array($when);

	$wc = $gc->newWebContent();
	$wc->url = $url;
	$wc->height = $height;
	$wc->width = $width;

	$wcLink = $gc->newLink();
	$wcLink->rel = "http://schemas.google.com/gCal/2005/webContent";
	$wcLink->title = $title;
	$wcLink->type = $type;
	$wcLink->href = $icon;

	$wcLink->webContent = $wc;
	$newEntry->link = array($wcLink);

	$createdEntry = $gc->insertEvent($newEntry);
	return $createdEntry->id->text;
}

/**
 * Creates a recurring event on the authenticated user's default calendar with
 * the specified event details.
 *
 * @param  Zend_Http_Client $client    The authenticated client object
 * @param  string           $title     The event title
 * @param  string           $desc      The detailed description of the event
 * @param  string           $where
 * @param  string           $recurData The iCalendar recurring event syntax (RFC2445)
 * @return void
 */
function createRecurringEvent ($client, $title = 'Tennis with Beth',
$desc='Meet for a quick lesson', $where = 'On the courts',
$recurData = null)
{
	$gc = new Zend_Gdata_Calendar($client);
	$newEntry = $gc->newEventEntry();
	$newEntry->title = $gc->newTitle(trim($title));
	$newEntry->where = array($gc->newWhere($where));

	$newEntry->content = $gc->newContent($desc);
	$newEntry->content->type = 'text';

	/**
	 * Due to the length of this recurrence syntax, we did not specify
	 * it as a default parameter value directly
	 */
	if ($recurData == null) {
		$recurData =
        "DTSTART;VALUE=DATE:20070501\r\n" .
        "DTEND;VALUE=DATE:20070502\r\n" .
        "RRULE:FREQ=WEEKLY;BYDAY=Tu;UNTIL=20070904\r\n";
	}

	$newEntry->recurrence = $gc->newRecurrence($recurData);

	$gc->post($newEntry->saveXML());
}

/**
 * Returns an entry object representing the event with the specified ID.
 *
 * @param  Zend_Http_Client $client  The authenticated client object
 * @param  string           $eventId The event ID string
 * @return Zend_Gdata_Calendar_EventEntry|null if the event is found, null if it's not
 */
function getEvent($client, $eventId)
{
	$gdataCal = new Zend_Gdata_Calendar($client);
	$query = $gdataCal->newEventQuery();
	$query->setUser('default');
	$query->setVisibility('private');
	$query->setProjection('full');
	$query->setEvent($eventId);

	try {
		$eventEntry = $gdataCal->getCalendarEventEntry($query);
		return $eventEntry;
	} catch (Zend_Gdata_App_Exception $e) {
		var_dump($e);
		return null;
	}
}

/**
 * Updates the title of the event with the specified ID to be
 * the title specified.  Also outputs the new and old title
 * with HTML br elements separating the lines
 *
 * @param  Zend_Http_Client $client   The authenticated client object
 * @param  string           $eventId  The event ID string
 * @param  string           $newTitle The new title to set on this event
 * @return Zend_Gdata_Calendar_EventEntry|null The updated entry
 */
function updateEvent ($client, $eventId, $newTitle)
{
	$gdataCal = new Zend_Gdata_Calendar($client);
	if ($eventOld = getEvent($client, $eventId)) {
		echo "Old title: " . $eventOld->title->text . "<br />\n";
		$eventOld->title = $gdataCal->newTitle($newTitle);
		try {
			$eventOld->save();
		} catch (Zend_Gdata_App_Exception $e) {
			var_dump($e);
			return null;
		}
		$eventNew = getEvent($client, $eventId);
		echo "New title: " . $eventNew->title->text . "<br />\n";
		return $eventNew;
	} else {
		return null;
	}
}

/**
 * Adds an extended property to the event specified as a parameter.
 * An extended property is an arbitrary name/value pair that can be added
 * to an event and retrieved via the API.  It is not accessible from the
 * calendar web interface.
 *
 * @param  Zend_Http_Client $client  The authenticated client object
 * @param  string           $eventId The event ID string
 * @param  string           $name    The name of the extended property
 * @param  string           $value   The value of the extended property
 * @return Zend_Gdata_Calendar_EventEntry|null The updated entry
 */
function addExtendedProperty ($client, $eventId,
$name='http://www.example.com/schemas/2005#mycal.id', $value='1234')
{
	$gc = new Zend_Gdata_Calendar($client);
	if ($event = getEvent($client, $eventId)) {
		$extProp = $gc->newExtendedProperty($name, $value);
		$extProps = array_merge($event->extendedProperty, array($extProp));
		$event->extendedProperty = $extProps;
		$eventNew = $event->save();
		return $eventNew;
	} else {
		return null;
	}
}


/**
 * Adds a reminder to the event specified as a parameter.
 *
 * @param  Zend_Http_Client $client  The authenticated client object
 * @param  string           $eventId The event ID string
 * @param  integer          $minutes Minutes before event to set reminder
 * @return Zend_Gdata_Calendar_EventEntry|null The updated entry
 */
function setReminder($client, $eventId, $minutes=15)
{
	$gc = new Zend_Gdata_Calendar($client);
	$method = "alert";
	if ($event = getEvent($client, $eventId)) {
		$times = $event->when;
		foreach ($times as $when) {
			$reminder = $gc->newReminder();
			$reminder->setMinutes($minutes);
			$reminder->setMethod($method);
			$when->reminders = array($reminder);
		}
		$eventNew = $event->save();
		return $eventNew;
	} else {
		return null;
	}
}

/**
 * Deletes the event specified by retrieving the atom entry object
 * and calling Zend_Feed_EntryAtom::delete() method.  This is for
 * example purposes only, as it is inefficient to retrieve the entire
 * atom entry only for the purposes of deleting it.
 *
 * @param  Zend_Http_Client $client  The authenticated client object
 * @param  string           $eventId The event ID string
 * @return void
 */
function deleteEventById ($service, $url, $eventId)
{
	$eventURL = $eventId;
	try {
		$event = $service->getCalendarEventEntry($eventURL);
		$event->delete($eventId);
	} catch (Zend_Gdata_App_Exception $e) {
		echo "Error: " . $e->getMessage();
	}

}

/**
 * Deletes the event specified by calling the Zend_Gdata::delete()
 * method.  The URL is typically in the format of:
 * http://www.google.com/calendar/feeds/default/private/full/<eventId>
 *
 * @param  Zend_Http_Client $client The authenticated client object
 * @param  string           $url    The url for the event to be deleted
 * @return void
 */
function deleteEventByUrl ($client, $url)
{
	$gdataCal = new Zend_Gdata_Calendar($client);
	$gdataCal->delete($url);
}
?>